package org.adorsys.aderp.orga.web.ext;

import java.io.IOException;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.adorsys.aderp.aderplogin.roles.ContextualRoleVoter;
import org.adorsys.aderp.aderplogin.roles.SimpleContextualAttrEval;
import org.adorsys.aderp.jpa.security.SecurityUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping({"/home", "/", "/index"})
@Controller
public class HomeController {
	
	private SimpleContextualAttrEval rolePPSuport = new SimpleContextualAttrEval("PP_ADERPORGA_SUPPORT");
	private SimpleContextualAttrEval rolePPUser = new SimpleContextualAttrEval("PP_ADERPORGA_USER");
	private SimpleContextualAttrEval rolePPBackOffice = new SimpleContextualAttrEval("PP_ADERPORGA_BACKOFFICE");

	private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
	public static final String INDEX_PAGE = "index";

	@RequestMapping(method = RequestMethod.GET)
	public String selectPage(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	UserDetails userDetails = SecurityUtils.getUserDetails();
    	if(userDetails==null) return INDEX_PAGE;
    	Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
    	for (GrantedAuthority grantedAuthority : authorities) {
			if(ContextualRoleVoter.ACCESS_GRANTED == rolePPUser.match(grantedAuthority.getAuthority())){
				redirectStrategy.sendRedirect(request, response, "/user");
				return null;
			} else if (ContextualRoleVoter.ACCESS_GRANTED == rolePPBackOffice.match(grantedAuthority.getAuthority())){
				redirectStrategy.sendRedirect(request, response, "/backoffice");
				return null;
			} else if (ContextualRoleVoter.ACCESS_GRANTED == rolePPSuport.match(grantedAuthority.getAuthority())){
				redirectStrategy.sendRedirect(request, response, "/support");
				return null;
			}
		}
    	return INDEX_PAGE;
	}
}
